#!/usr/bin/env python
"""
调试登录问题
"""
import os
import sys
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inter_api.settings')
django.setup()

from django.contrib.auth import get_user_model, authenticate
from students.models import Student

User = get_user_model()

def debug_login_issue():
    """调试登录问题"""
    print("调试登录问题...")
    
    # 查找学生数据
    print("\n=== 查找学生数据 ===")
    try:
        student = Student.objects.get(student_id='CS2024001')
        print(f"找到学生: {student}")
        print(f"学生ID: {student.id}")
        print(f"学号: {student.student_id}")
        print(f"姓名: {student.name}")
        print(f"手机: {student.phone}")
        print(f"邮箱: {student.email}")
        print(f"关联用户: {student.user}")
        
        if student.user:
            user = student.user
            print(f"\n=== 关联用户信息 ===")
            print(f"用户ID: {user.id}")
            print(f"用户名: {user.username}")
            print(f"邮箱: {user.email}")
            print(f"手机: {user.phone}")
            print(f"角色: {user.role}")
            print(f"是否激活: {user.is_active}")
            print(f"是否有密码: {user.password != ''}")
            print(f"密码哈希: {user.password[:50]}...")
            
            # 测试密码验证
            print(f"\n=== 密码验证测试 ===")
            test_passwords = ['123456', 'testpass123', 'password']
            for pwd in test_passwords:
                is_valid = user.check_password(pwd)
                print(f"密码 '{pwd}': {'✅ 正确' if is_valid else '❌ 错误'}")
        else:
            print("❌ 学生没有关联用户账号")
            
    except Student.DoesNotExist:
        print("❌ 没有找到学号为 CS2024001 的学生")
        
        # 查看所有学生
        print("\n=== 所有学生列表 ===")
        students = Student.objects.all()[:10]
        for s in students:
            print(f"学号: {s.student_id}, 姓名: {s.name}, 用户: {s.user}")
    
    # 查找用户数据
    print("\n=== 查找用户数据 ===")
    
    # 按不同方式查找用户
    identifiers = ['CS2024001', '张三', '13800138001', 'zhangsan@opstu.edu.cn']
    
    for identifier in identifiers:
        print(f"\n--- 查找标识符: {identifier} ---")
        
        # 直接查找用户
        try:
            user = User.objects.get(username=identifier)
            print(f"✅ 通过用户名找到: {user}")
        except User.DoesNotExist:
            print(f"❌ 用户名查找失败")
        
        try:
            user = User.objects.get(email=identifier)
            print(f"✅ 通过邮箱找到: {user}")
        except User.DoesNotExist:
            print(f"❌ 邮箱查找失败")
        
        try:
            user = User.objects.get(phone=identifier)
            print(f"✅ 通过手机找到: {user}")
        except User.DoesNotExist:
            print(f"❌ 手机查找失败")
        
        # 通过学生查找
        try:
            student = Student.objects.get(student_id=identifier)
            if student.user:
                print(f"✅ 通过学号找到用户: {student.user}")
            else:
                print(f"❌ 学生存在但没有关联用户")
        except Student.DoesNotExist:
            print(f"❌ 学号查找失败")
        
        try:
            student = Student.objects.get(phone=identifier)
            if student.user:
                print(f"✅ 通过学生手机找到用户: {student.user}")
            else:
                print(f"❌ 学生存在但没有关联用户")
        except Student.DoesNotExist:
            print(f"❌ 学生手机查找失败")
        
        try:
            student = Student.objects.get(email=identifier)
            if student.user:
                print(f"✅ 通过学生邮箱找到用户: {student.user}")
            else:
                print(f"❌ 学生存在但没有关联用户")
        except Student.DoesNotExist:
            print(f"❌ 学生邮箱查找失败")
    
    # 测试认证后端
    print("\n=== 测试认证后端 ===")
    from accounts.backends import MultiFieldAuthBackend
    
    backend = MultiFieldAuthBackend()
    
    for identifier in identifiers:
        print(f"\n--- 测试认证: {identifier} ---")
        user = backend._get_user_by_identifier(identifier)
        if user:
            print(f"✅ 认证后端找到用户: {user}")
            
            # 测试完整认证
            auth_user = authenticate(username=identifier, password='123456')
            if auth_user:
                print(f"✅ 完整认证成功: {auth_user}")
            else:
                print(f"❌ 完整认证失败（密码错误）")
        else:
            print(f"❌ 认证后端未找到用户")

if __name__ == '__main__':
    debug_login_issue()
